package com.xdf.ecommerce.service.communication;

import com.alibaba.fastjson.JSON;
import com.xdf.ecommerce.constant.CommonConstant;
import com.xdf.ecommerce.vo.JwtToken;
import com.xdf.ecommerce.vo.UsernameAndPassword;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * 使用 RestTemplate 的方式实现微服务间的通信
 * 这种方式使用硬编码的IP地址和端口号，比较死板
 * @author chanchaw
 * @create 2025-10-29 9:31
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UseRestTemplateService {
    private final LoadBalancerClient loadBalancerClient;
    // 文件 AuthorityController.java 的 post 方法，通过 body 传参UsernameAndPassword
    // 这里 URI 中不可添加网关路径，后面使用负载均衡器查询到具体的授权服务器后直接填充了授权服务器的IP和端口号
    // 所以这里如果填写的网关路径 imooc，则请求不对了
    // 此处的URL直接填写授权服务器的URL，两个占位符等待负载均衡器填充
    private static final String URL_LOGIN_GET_TOKEN = "http://[host]:[port]/ecommerce-authority-center/authority/token";
    public JwtToken getToken(UsernameAndPassword usernameAndPassword){
        String url = URL_LOGIN_GET_TOKEN.replace("[host]", "localhost").replace("[port]", "7000");
        return getToken(usernameAndPassword,url);
    }
    public JwtToken getToken(UsernameAndPassword usernameAndPassword,String url){
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        return new RestTemplate().postForObject(
                url, new HttpEntity<>(JSON.toJSON(usernameAndPassword),httpHeaders),
                JwtToken.class
        );
    }
    // 通过负载均衡器获取 token
    public JwtToken getToken8LoadBalancer(UsernameAndPassword usernameAndPassword){
        ServiceInstance serviceInstance = loadBalancerClient.choose(CommonConstant.AUTHORITY_CENTER_SERVICE_ID);
        log.info("通过loadBalancerClient获取到授权服务ID,实例ID:[{}],[{}]", serviceInstance.getServiceId(),serviceInstance.getInstanceId());
        String url = URL_LOGIN_GET_TOKEN.replace("[host]", serviceInstance.getHost()).replace("[port]", new Integer(serviceInstance.getPort()).toString());
        log.info("通过负载均衡获取到的服务器填充后的请求URL：[{}]", url);
        return getToken(usernameAndPassword, url);
    }
}
